<template>
  <div>
    <!-- 右边基本表格 -->
    <BasicTable @register="registerTable">
      <!-- 表格标题 -->
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ title }} </span>
      </template>
      <!-- <template #footer> 底部+{{ registerTable }}</template> -->
      <!-- 表格右上角自定义按钮（新增...） -->
      <template #toolbar>
        <a-button
          v-for="(item, index) in butData"
          :key="index"
          :type="item.type"
          @click="item.do"
          v-auth="item.auth"
        >
          <Icon :icon="item.icon" /> {{ item.title }}
        </a-button>
      </template>
      <!-- 表格插槽 -->
      <template #upload="{ record }">
        <BasicUpload
          v-model:value="record.dataMap"
          :bizKey="record.id"
          :bizType="'m8OrderPic_file'"
          :readonly="true"
        />
      </template>
      <template #remarks="{ record }">
        <a-button @click="handleRemarks(record)" v-auth="'m8:order:pic:viewRemark'">
          <Icon icon="simple-line-icons:pencil" />
        </a-button>
        {{ record.remarks }}
      </template>

      <template #jcjy="{ record }">
        <!-- @click="handleForm({ roleCode: record.roleCode_like, op: 'edit' })" -->
        <!-- <a style="display: flex; line-height: 30px" @click="orderCheckList(record.id)">
          <Icon
            icon="ant-design:fast-forward-outlined"
            style="margin-right: 10px; font-size: 30px"
          />
          检验明细
        </a> -->
        <a-button @click="orderCheckList(record.id)" v-auth="'m8:machine:check:view'">
          <Icon icon="ant-design:fast-forward-outlined" />检验明细
        </a-button>
      </template>

      <!-- 表格插槽 -->
      <template #picno="{ record }">
        <a @click="handleForm({ id: record.id })">
          {{ record.picname }}
        </a>
      </template>

      <template #order="{ record }">
        <!-- <a v-if="!props.data.id" @click="handleOrder({ ccode: record.orderCode })">
          {{ record.orderCode }}
        </a> -->
        <a v-if="!props.data.id" @click="handleOrder({ id: record.order.id })">
          {{ record.orderCode }}
        </a>
        <div v-else>{{ record.orderCode }}</div>
      </template>
    </BasicTable>
    <!-- 页签方式编辑 -->
    <InputFormTabs @register="registerDrawer2" @success="handleSuccess" />

    <OrderFormTabs @register="registerOrderFormDrawer" @success="handleSuccess" />
    <Modal @register="register" @success="handleSuccess" />

    <BasicModal
      @register="register1"
      :title="'关联工艺'"
      width="60%"
      :showFooter="true"
      @ok="handleSubmit"
    >
      <Route ref="routeList" :data="routeData" @success="handleSuccess" />
    </BasicModal>

    <BasicModal
      @register="register2"
      :title="'添加图纸备注信息'"
      width="60%"
      :showFooter="true"
      :okAuth="'m8:order:pic:editRemark'"
      @ok="remarksSubmit"
    >
      <BasicForm @register="registerForm" />
    </BasicModal>

    <RouteForm @register="registerDrawer3" />
    <PrintModal @register="registerPrintModal" />
    <!-- 检验数 -->
    <BasicDrawer
      v-bind="$attrs"
      @register="registerCheckDrawer"
      :showFooter="false"
      width="80%"
      title="检验明细"
    >
      <CheckList :orderPic="orderPic" />
    </BasicDrawer>

    <!-- 图纸备注 -->
    <BasicDrawer
      v-bind="$attrs"
      @register="registerRemarksDrawer"
      :showFooter="false"
      width="80%"
      :maskClosable="true"
      title="图纸备注"
    >
      <Remarks :picId="picId" />
    </BasicDrawer>

    <!-- 订单状态 -->
    <BasicDrawer
      v-bind="$attrs"
      @register="registerOrderStatusDrawer"
      :showFooter="true"
      width="80%"
      :maskClosable="true"
      :showOkBtn="false"
      title="图纸状态"
    >
      <OrderStatus :picId="picId" />
    </BasicDrawer>
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsM8OrderPicList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, onMounted, ref } from 'vue';
  // import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable, ActionItem } from '/@/components/Table';
  import { listSet, customListData } from '/@/api/test/testData';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import InputFormTabs from './formTabs.vue';
  import OrderFormTabs from '../order/formTabs.vue';
  import OrderStatus from '/@/views/m8/order/order/orderEdit/orderStatus/list.vue';
  import { schemasData, tabConfigData } from '/@/utils/custom';
  import { orderPicDelete, addRemarks } from '/@/api/order/order';
  import { useModal } from '/@/components/Modal';
  import { BasicModal } from '/@/components/Modal';
  import { BasicDrawer } from '/@/components/Drawer';
  import Modal from './Modal.vue';
  import Route from '/@/views/bas/route/list.vue?routeType=0';
  import RouteForm from '/@/views/m8/order/pic/m8OrderRoute/form.vue';
  import Remarks from '/@/views/m8/order/remarks.vue';
  import { BasicUpload } from '/@/components/Upload';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { officeTreeData } from '/@/api/sys/office';
  import { usePermission } from '/@/hooks/web/usePermission';
  import PrintModal from '/@/components/print/printModal.vue';

  import CheckList from '../flow/check/list.vue';
  import { nextTick } from 'vue';
  import { handleExport } from '/@/utils/export';

  const [registerPrintModal, { openModal: openPrintModal }] = useModal();
  const { hasPermission } = usePermission();
  // const { t } = useI18n('test.testData');
  const { showMessage } = useMessage();
  const visible = ref<boolean>(false);
  let routeData = ref<any>();
  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 6, md: 8 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    showAdvancedButton: true,
    schemas: [],
  });
  let tableColumns = ref<any>([]);
  // const tableDataSource = ref<Recordable[]>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});
  const getTitle = ref({
    // 表格标题图标
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: listTabConfig.value.title,
  });
  let title = ref('');
  let orderPic = ref('');
  let picId = ref('');

  const actionColumn: BasicColumn = {
    width: 320, //操作按钮宽度
    actions: (record: Recordable) => [
      {
        icon: 'clarity:note-edit-line',
        title: '编辑订单图纸',
        onClick: handleForm.bind(this, { id: record.id }),
        auth: 'm8:order:pic:edit',
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: '删除订单图纸',
        popConfirm: {
          title: '是否确认删除数据',
          confirm: handleDelete.bind(this, { id: record.id }),
        },
        auth: 'm8:order:pic:delete',
      },

      {
        // icon: 'clarity:note-edit-line',
        label: '图纸备注',
        onClick: remarksPush.bind(this, record),
        auth: 'm8:order:pic:viewRemark',
      },
      {
        // icon: 'clarity:note-edit-line',
        label: record.bsetRoute == '1' ? '查看工艺' : '关联工艺',
        // title: '关联工艺',
        onClick: routerList.bind(this, record),
        auth: 'm8:orderRoute:view',
      },
      {
        label: '查看状态',
        onClick: handleStatus.bind(this, record),
        auth: 'm8:orderRoute:view',
      },
    ],
  };

  const props = defineProps({
    data: { type: Object, default: {} },
  });

  onMounted(async () => {
    const res = await listSet({ viewCode: 'M8_order_pic_list' });
    title.value = res.layVoucherView.name;
    layVoucherView.value = res.layVoucherView;

    searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);

    tableColumns.value = layVoucherView.value.flistTabCols; //表格表头

    butData.value = layVoucherView.value.headBtns; //表格右上角按钮

    butData.value.forEach((item) => {
      if (item.btnKey == 'btnAdd') {
        item.do = () => handleForm({});
      } else if (item.btnKey == 'btnBatchAdd') {
        item.do = () =>
          openModal(true, { title: item.title, btnKey: item.btnKey, 'order.id': props.data.id });
      } else if (item.btnKey == 'btnEditPrice') {
        item.do = () => openModal(true, { title: item.title, 'order.id': props.data.id });
      } else if (item.btnKey == 'btnPrint') {
        item.do = () => handlePrint();
      } else if (item.btnKey == 'btnExport') {
        item.do = () => btnExport();
      }
    });

    actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮
    actionColumnData.value.push({
      // color: 'default',
      // icon: 'fa fa-link', //图标代码
      label: '关联工艺',
      title: '关联工艺', //按钮显示内容
    });

    listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
    setProps({
      api: customListData,
      beforeFetch: (params) => {
        // console.log(listTabConfig.value.api);
        params.url = listTabConfig.value.api;
        // console.log(params, '123456'); //查询列表参数信息
        params['order.id'] = props.data.id;
        return params;
      },
      autoCreateKey: listTabConfig.value.autoCreateKey,
      bordered: listTabConfig.value.bordered,
      canResize: listTabConfig.value.canResize,
      clearSelectOnPageChange: listTabConfig.value.clearSelectOnPageChange,
      clickToRowSelect: listTabConfig.value.clickToRowSelect,
      ellipsis: listTabConfig.value.ellipsis,
      emptyDataIsShowTable: listTabConfig.value.emptyDataIsShowTable,
      inset: listTabConfig.value.inset,
      isTreeTable: listTabConfig.value.isTreeTable,
      pagination: listTabConfig.value.pagination,
      showIndexColumn: listTabConfig.value.showIndexColumn,
      showSummary: listTabConfig.value.showSummary,
      showTableSetting: listTabConfig.value.showTableSetting,
      striped: listTabConfig.value.striped,
      useSearchForm: listTabConfig.value.useSearchForm,
      tableSetting: listTabConfig.value.tableSetting,
      titleHelpMessage: listTabConfig.value.titleHelpMessage,
      maxHeight: listTabConfig.value.maxHeight,
      resizeHeightOffset: props.data.id ? listTabConfig.value.resizeHeightOffset : 0,
    });
    setTimeout(() => {
      getForm().setFieldsValue({
        picno: props.data.picno,
      });
    }, 0);
    if (!listTabConfig.value.immediate) {
      reload({
        searchInfo: {
          picno: props.data.picno,
        },
      });
    }
  });
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: [
      {
        field: 'id',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        // required: true,
        colProps: { lg: 12, md: 24 },
        show: false,
      },
      {
        label: '历史备注',
        field: 'p_oldRemarks',
        component: 'InputTextArea',
        componentProps: {
          maxlength: 200,
          rows: 7,
        },
        // dynamicDisabled:() => hasPermission('m8:order:pic:editRemark'),
        // required: true,
        colProps: { lg: 12, md: 24 },
      },
      {
        label: '最新备注',
        field: 'p_addRemarks',
        component: 'InputTextArea',
        componentProps: {
          maxlength: 200,
          rows: 7,
        },
        // rules: [{ required: true }],
        colProps: { lg: 12, md: 24 },
      },
      {
        label: '指定负责人',
        field: 'createByCode',
        fieldLabel: 'createByName',
        component: 'TreeSelect',
        required: true,
        componentProps: {
          api: officeTreeData,
          params: { isLoadUser: true, userIdPrefix: '', isAll: true },
          canSelectParent: false,
          allowClear: true,
        },
        colProps: { lg: 12, md: 24 },
      },
    ],
    baseColProps: { lg: 24, md: 24 },
  });
  // const tableDataSource = ref<Recordable[]>([]);
  const [register1, { openModal: openModal1, closeModal }] = useModal();
  const [register2, { openModal: openModal2, closeModal: closeModal2, setModalProps }] = useModal();
  // const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerOrderFormDrawer, { openDrawer: openOrderFormDrawer }] = useDrawer();
  const [registerDrawer2, { openDrawer: openDrawer2 }] = useDrawer();
  const [registerDrawer3, { openDrawer: openDrawer3 }] = useDrawer();
  const [registerCheckDrawer, { openDrawer: openCheckDrawer }] = useDrawer();
  const [registerRemarksDrawer, { openDrawer: openRemarkskDrawer }] = useDrawer();
  const [registerOrderStatusDrawer, { openDrawer: openOrderStatusDrawer }] = useDrawer();

  const [registerTable, { reload, getForm, setProps, getSelectRows }] = useTable({
    actionColumn: actionColumn,
    columns: tableColumns,
    formConfig: searchForm.value as FormProps,
    rowSelection: {
      type: 'checkbox',
    },
  });

  const [register, { openModal }] = useModal();

  function routerList(record) {
    if (record.bsetRoute == '1') {
      openDrawer3(true, { id: record.id });
    } else {
      if (hasPermission(['m8:orderRoute:edit'])) {
        routeData.value = record;
        routeData.value.flag = '0';
        visible.value = true;
        openModal1(true, '');
      } else {
        showMessage('当前图纸未配置工艺路线');
      }
    }
  }

  // 刷新表格数据（含表单回调）
  function handleSuccess() {
    closeModal();
    reload();
  }

  function remarksPush(record) {
    picId.value = record.id;
    openRemarkskDrawer(true);
  }

  function handleOrder(record) {
    openOrderFormDrawer(true, record);
  }

  async function handleRemarks(record: Recordable) {
    await openModal2(true, '');
    await resetFields();
    await setFieldsValue({ p_oldRemarks: record.remarks, id: record.id });
  }
  async function remarksSubmit() {
    try {
      const data = await validate();
      setModalProps({ confirmLoading: true });
      const res = await addRemarks(data);
      showMessage(res.message);
      setTimeout(closeModal2);
      reload();
      // emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage('您填写的信息有误，请根据提示修正。');
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function handleForm(record: Recordable) {
    openDrawer2(true, record);
  }

  let routeList = ref<any>(null);

  function handleSubmit() {
    setTimeout(closeModal);
    var o = routeList.value.openRouteForm();
  }

  defineExpose({
    handleSuccess,
  });

  async function handleDelete(record: Recordable) {
    const res = await orderPicDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  function handleRouteForm(record) {
    openDrawer3(true, { id: record.id });
  }
  function orderCheckList(record) {
    orderPic.value = record;
    openCheckDrawer(true);
  }

  //导出数据
  function btnExport() {
    var formdata = getForm().getFieldsValue();
    formdata = { ...formdata, 'order.id': props.data.id };
    handleExport('/m8/order/pic/exportData', formdata);
  }

  // 打印
  const handlePrint = () => {
    let rows = getSelectRows();
    if (rows.length <= 0) {
      showMessage('请至少选择一条要打印的数据!');
    } else {
      let ids = '';
      rows.map((item) => {
        if (ids == '') {
          ids = item.id;
        } else {
          ids = ids + ',' + item.id;
        }
      });
      let obj = {
        title: '图纸二维码打印',
        ids: ids,
        height: '0.8',
        width: '0.4',
        fileName: 'printPic',
      };
      openPrintModal(true, obj);
    }
  };

  // 查看图纸状态
  function handleStatus(record) {
    picId.value = record.id;
    openOrderStatusDrawer(true);
  }
</script>
<style>
  .jeesite-editable-cell__action {
    display: none;
  }

  .edit-cell-align-center {
    width: 100% !important;
  }
</style>
